$cat = {
	load : function() {
		$store.get({
			url : '/admin/store/load',
			data : null,
			success : function(d) {
				if (d == null)
					return;
				// refresh the table
				$('#store-table').remove();

				var table = $('#table-template').clone();
				table.attr('id', 'store-table');
				table.css('display', 'block').appendTo('#page-root');
				for ( var i = 0; i < d.length; i++) {
					var c = d[i];
					var row = table.find('tr.store-row:first').clone();
					row.removeClass('hide');
					table.append(row);
					row.find('td::nth-child(1)').text(c.storeId);
					row.find('td:nth-child(2)').text(c.name);
					row.find('td:nth-child(3)').text(c.contactPerson);
					row.find('td:nth-child(4)').text(c.phoneNumber);
					row.find('td:nth-child(5)').text(c.locality);
				}
				table.find('tr:odd').css('background-color', '#cabcab');
				$('a[title="edit"]').click(function() {
					var $this = $(this).closest('tr');
					$('#store-id').val($this.find('td:nth-child(1)').text());
					$store.get({
						url : '/admin/store/load/single',
						data : JSON.stringify({
							storeId : $('#store-id').val()
						}),
						success : function(store) {
							$('#name').val(store.name);
							$('#house').val(store.house);
							$('#building').val(store.building);
							$('#street').val(store.street);
							$('#locality').val(store.locality);
							$('#city').val(store.city);
							$('#contact-person').val(store.contactPerson);
							$('#number').val(store.phoneNumber);
							$('#email').val(store.email);
							$('#desc').val(store.description);
							$('#tin').val(store.tin);
							$('#tagline').val(store.tagline);
						},
						error : function(e) {
							alert('error loading store data');
						}
					});
				});
			},
			error : function(e) {
				alert('error loading stores');
			}
		});
	},
	save : function() {
		var form = $('#store-form');
		$store.post({
			url : '/admin/store/save',
			data : form.serialize(),
			success : function(d) {
				alert('done');
				$('#store-id').val(null);
				$cat.load();
			},
			error : function(e) {
				alert('error saving store');
			}
		});
	}
};
$(document).ready(function() {
	$cat.load();
	$('#save-button').click(function() {
		$cat.save();
	});
	$('#reset-button').click(function() {
		$('#brand-id').val(null);
	});
});